package superpay

import (
    "errors"
	"encoding/json"
	"thirdpaysdk/core"
	"thirdpaysdk/utils/signature"
	"thirdpaysdk/utils/mapstruct"
	"github.com/astaxie/beego"
)

type RefundReq struct {
	Service        string   `json:"service"`             
	MchId          string   `json:"mch_id"`           
	Charset        string   `json:"charset"`   
	SignType       string   `json:"sign_type"`
	Sign           string   `json:"sign"`            
	Memo           string   `json:"memo,omitempty"`
	Version        string   `json:"version"`      
	CallBackUrl    string   `json:"call_back_url"`        
	MchOrderNo     string   `json:"mch_order_no"`
	OrigMchOrderNo string   `json:"orig_mch_order_no"`       
	RefundAmount   string   `json:"refund_amount"`
	RefundNote     string   `json:"refund_note,omitempty"`
	NotifyUrl      string   `json:"notify_url,omitempty"`
}

type RefundData struct {
	Result   bool    `json:"result"`
	Sign     string  `json:"sign"`
	SignType string  `json:"sign_type"`
}
	
type RefundResp struct {
	Status  string           `json:"status"`
	Message string           `json:"message"`
	Data    json.RawMessage  `json:"data"`
}

func Refund(mchId,appSecret,callBackUrl,mchOrderNo,origMchOrderNo,refundAmount string) (RefundResp,error){
	url := "https://gate.supaytechnology.com/api/gateway/merchant/order"
	client := core.GetPayJSONClient("POST", url)
	var rsp RefundResp
	var req = new(RefundReq)
	//
	req.Service = "create_refund"
	req.MchId = mchId
	req.Charset = "UTF-8"
	req.SignType = "MD5"
	req.Memo = ""
	req.Version = "1.0"
	//
	req.CallBackUrl = callBackUrl
	req.MchOrderNo = mchOrderNo             
	req.OrigMchOrderNo = origMchOrderNo        
	req.RefundAmount = refundAmount
	req.RefundNote = ""
	req.NotifyUrl = ""
	//
	params := mapstruct.Struct2Map(req, "json")
	req.Sign = signature.SuperPayMakeSign(params, appSecret)
	tbData, err := client.PayJsonExcute(req, &rsp)
    beego.Debug("Refund:", string(tbData))
	if err != nil {
		return rsp, err
	}
	if rsp.Status != "T" {
	    returnMsg := rsp.Message
		return rsp, errors.New(returnMsg)
	}
	var refundData RefundData
	err = json.Unmarshal(rsp.Data, &refundData)
	if err != nil {
		return rsp, err
	}
	if !refundData.Result {
		return rsp, errors.New("refund is not success")
	}
	// 校验回执签名
	/*
	rspMap :=  mapstruct.Struct2Map(rsp, "json")
	sign := signature.SuperPayMakeSign(rspMap, appSecret)
	if rsp.Data.Sign != sign {
		err = errors.New("response sign err")
		return rsp, err
	}
	*/
	return rsp, nil
}
